<!--<template>-->
<!--  <div id="add_sos">-->
<!--    <div class="top">-->
<!--      <van-icon @click="toSecurityCenter()" name="arrow-left"/>-->
<!--      <div class="title">实名认证</div>-->
<!--    </div>-->
<!--    <div class="content">-->
<!--      <van-form @submit="onSubmit">-->
<!--        <div class="title">姓名:</div>-->
<!--        <van-field-->
<!--            v-model="form.name"-->
<!--            name="name"-->
<!--            placeholder="请输入姓名"-->
<!--            :rules="[{ required: true, message: '请输入姓名' }]"-->
<!--        />-->
<!--        <div class="title">身份证号:</div>-->
<!--        <van-field-->
<!--            v-model="form.attestation"-->
<!--            name="attestation"-->
<!--            placeholder="请输入身份证号"-->
<!--            :rules="[{ required: true, message: '请输入身份证号' }]"-->
<!--        />-->
<!--        <div class="bind">-->
<!--          <van-button round block type="info" native-type="submit">认证</van-button>-->
<!--        </div>-->
<!--      </van-form>-->
<!--    </div>-->

<!--    <div>-->
<!--      <van-uploader v-model="fileList" :after-read="afterRead"/>-->
<!--      <div class="upload">-->
<!--        <van-button type="primary" @click="uploadFile">开始认证</van-button>-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
<!--</template>-->

<!--<script>-->

<!--import {addAttestation} from "@/api/purse/add_sos";-->
<!--import axios from "axios";-->

<!--export default {-->
<!--  data() {-->
<!--    return {-->
<!--      fileList: [],-->
<!--      form: {-->
<!--        name: '',-->
<!--        userId: '',-->
<!--        attestation: '',-->
<!--      },-->
<!--    };-->
<!--  },-->
<!--  methods: {-->
<!--    uploadFile() {-->
<!--    },-->
<!--    afterRead(file) {-->
<!--      axios.post('http://localhost:8083/file/upload', file, {headers: {'Content-Type': 'multipart/form-data'}})-->
<!--          .then(response => {-->
<!--            console.log(response.data);-->
<!--            // 可以根据实际情况进行成功后的处理-->
<!--          })-->
<!--          .catch(error => {-->
<!--            console.error(error);-->
<!--            // 可以根据实际情况进行失败后的处理-->
<!--          });-->
<!--    },-->
<!--    toSecurityCenter() {-->
<!--      this.$router.go(-1);-->
<!--    },-->
<!--    onSubmit(values) {-->
<!--      this.form.name = values.name;-->
<!--      this.form.attestation = values.attestation;//11010119900101123X-->
<!--      const regex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9X]$/;-->
<!--      if (regex.test(this.form.attestation)) {-->
<!--        this.form.userId = localStorage.getItem("userId");-->
<!--        addAttestation(this.form).then(res => {-->
<!--          if (res.code === 1) {-->
<!--            this.$toast.success('认证成功');-->
<!--            this.$router.go(-1);-->
<!--          } else {-->
<!--            this.$toast.fail('认证失败');-->
<!--          }-->
<!--        });-->
<!--      } else {-->
<!--        this.$toast.fail('身份证格式错误');-->
<!--      }-->
<!--    },-->
<!--  },-->
<!--  created() {-->
<!--  },-->
<!--};-->
<!--</script>-->

<!--<style>-->
<!--body {-->
<!--  background-color: #F3FCFF;-->

<!--  #add_sos {-->
<!--    width: 100%;-->
<!--    height: 100%;-->
<!--    display: flex;-->
<!--    flex-direction: column;-->
<!--    align-items: center;-->

<!--    .top {-->
<!--      width: 100%;-->
<!--      height: 66px;-->
<!--      background-color: white;-->
<!--      display: flex;-->
<!--      align-items: center;-->
<!--      justify-content: center;-->
<!--      position: fixed;-->
<!--      top: 0;-->

<!--      .van-icon {-->
<!--        font-size: 26px;-->
<!--        position: absolute;-->
<!--        left: 20px;-->
<!--      }-->

<!--      .title {-->
<!--        font-size: 20px;-->
<!--      }-->
<!--    }-->

<!--    .content {-->
<!--      width: 100%;-->
<!--      height: 100%;-->
<!--      display: flex;-->
<!--      flex-direction: column;-->
<!--      align-items: center;-->
<!--      justify-content: center;-->
<!--      margin-top: 66px;-->

<!--      .title {-->
<!--        font-size: 20px;-->
<!--        font-weight: bold;-->
<!--        margin: 10px 0;-->
<!--      }-->

<!--      .van-field {-->
<!--        width: 360px;-->
<!--        height: 60px;-->
<!--        margin: 0 0 10px 0;-->
<!--        border-radius: 10px;-->
<!--        border: 1px solid #CDCECE;-->
<!--        display: flex;-->
<!--        align-items: center;-->
<!--        justify-content: center;-->
<!--      }-->

<!--      .bind {-->
<!--        width: 360px;-->
<!--        height: 60px;-->
<!--        margin: 30px 0;-->

<!--        .van-button {-->
<!--          width: 100%;-->
<!--          height: 70%;-->
<!--          font-size: 16px;-->
<!--          background-color: #4EA9CB;-->
<!--        }-->
<!--      }-->
<!--    }-->
<!--  }-->
<!--}-->
<!--</style>-->

<template>
  <div class="shimingrenzheng">

    <div class="camera" v-if="camer">
      <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
      <canvas id="canvasCamera" style="display:none;" :width="videoWidth" :height="videoHeight"></canvas>
      <van-button type="primary" size="large" @click="getCompetence">打开摄像头</van-button>
      <van-button type="primary" size="large" @click="setImage">拍照</van-button>
      <van-button type="primary" size="large" @click="stopNavigator">关闭摄像头</van-button>
      <van-button type="primary" size="large" @click="off">关闭相机</van-button>
    </div>
    <van-nav-bar title="实名认证" left-arrow @click-left="goback"/>
    <div class="zhengmian" v-if="!(uploadedImages.length > 0)">
      <div class="zheng">
        <van-uploader :after-read="afterRead"/>
      </div>
      <div class="zheng-zi">上传证件正面</div>
    </div>
    <div v-if="uploadedImages.length > 0">
      <van-image v-for="image in uploadedImages" :key="image" :src="image"/>
    </div>
    <div class="fanmian" v-if="!(RealNameAuthenticationVo.certificateHandImage.length > 0)">
      <div class="fan">
        <div>
          <!--          <van-uploader capture="camera" :after-read="afterRead1"/>-->
          <van-button type="primary" size="large" @click="getCamera">拍照</van-button>
        </div>
      </div>
      <div class="fan-zi">手持证件正面</div>
    </div>
    <div v-if="RealNameAuthenticationVo.certificateHandImage.length > 0">
      <van-image :src="RealNameAuthenticationVo.certificateHandImage"/>
    </div>


    <div class="zheng-ti">
      <van-button @click="onSubmit">开始识别</van-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {addAttestation} from "@/api/purse/add_sos";

export default {
  name: "Real-NameAuthentication",

  data() {
    return {
      videoWidth: 300,
      videoHeight: 300,
      uploadedImages: [],
      img: {
        url: ''
      },
      camer: false,
      value: '',
      showPicker: false,
      certificationVo: {
        idcard: '',
        name: ''
      },
      RealNameAuthenticationVo: {
        pid: '',
        certificateImage: '',
        certificateHandImage: '',
        name: ''
      },
      form: {
        userId: '',
        path1: '',
        path2: ''
      },
    }
  },
  created() {

  },
  methods: {
    off() {
      this.camer = false;
      this.stopNavigator();
    },
    getCamera() {
      this.camer = true;
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this
      this.thisCancas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      var constraints = {
        audio: false,
        video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        _this.thisVideo.onloadedmetadata = function () {
          _this.thisVideo.play()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //  绘制图片（拍照功能）

    setImage() {
      var _this = this
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight)
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/png')
      _this.imgSrc = image
      const file = image
      const time = (new Date()).valueOf()
      const name = time + '.png'
      const conversions = this.base64ToFile(file, name)
      const data = new FormData()
      data.append('file', conversions)
      axios.post('http://localhost:8081/purse/file/upload', data, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
        console.log(data)
        if (res.data.code === 1) {
          _this.RealNameAuthenticationVo.certificateHandImage = res.data.data.url
        }
      })
    },
    // base64图片转file的方法（base64图片, 设置生成file的文件名）
    base64ToFile(base64, fileName) {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      const data = base64.split(',')
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      const type = data[0].match(/:(.*?);/)[1]
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      const suffix = type.split('/')[1]
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1])
      // 获取解码结果字符串的长度
      let n = bstr.length
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n)
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n)
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type
      })
      // 将File文件对象返回给方法的调用者
      return file
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
    },
    goback() {
      this.$router.go(-1);
    },
    afterRead(file) {
      axios.post('http://localhost:8081/purse/file/upload', file, {headers: {'Content-Type': 'multipart/form-data'}})
          .then(response => {
            // 假设服务器返回的图片 URL
            const imageUrl = response.data.data.url;
            this.img.url = imageUrl;
            this.RealNameAuthenticationVo.certificateImage = imageUrl;
            axios.post('http://localhost:8081/purse/file/idc', this.img).then(res => {
              if (res.data.ret !== 200) {
                this.$toast('请上传身份证正面')
                return;
              }
              this.uploadedImages.push(imageUrl);
              this.certificationVo.name = res.data.data.info.name;
              this.RealNameAuthenticationVo.name = res.data.data.info.name;
              this.certificationVo.idcard = res.data.data.info.idcard;
            }).catch(error => {
              console.error('上传的不是身份证正面', error);
            })
          })
          .catch(error => {
            console.error('上传失败：', error);
          });
    },
    onSubmit() {
      this.form.userId = localStorage.getItem("userId");
      this.form.path1 = this.RealNameAuthenticationVo.certificateImage;
      this.form.path2 = this.RealNameAuthenticationVo.certificateHandImage;
      addAttestation(this.form).then(res => {
        if (res.data === 1) {
          this.$toast('认证完成');
          this.$router.go(-1);
        } else {
          this.$toast(res.data.msg);
        }
      })
    },
    // afterRead1(file) {
    //   axios.post('http://localhost:11219/file/upload', file, {headers: {'Content-Type': 'multipart/form-data'}})
    //       .then(response => {
    //         this.RealNameAuthenticationVo.certificateHandImage = response.data.data.url;
    //       })
    // }
  }
}
</script>

<style>
.camera {
  z-index: 999;
  width: 100%;
  height: 100%;
}


.shimingrenzheng {
  width: 100%;
  height: 100%;
  top: 0%;
  /* 固定定位 */
  position: fixed;
  margin-top: 0;
  margin-bottom: 0;
  background-color: #E9E9E9;
  /* border: 1px solid red; */
}

.smrz-dier {
  width: 100%;
  height: 60px;
  float: left;
  margin-top: 30px;
  background-color: white;
  /* border: 1px solid red; */
}

.smrz-zheng {
  float: left;
  margin-top: 20px;
  margin-left: 20px;
}

.jin-zheng {
  float: right;
  margin-top: 20px;
  margin-right: 20px;
  color: darkgray;
}

.zhengmian {
  width: 100%;
  height: 170px;
  float: left;
  margin-top: 20px;
  background-color: white;
}

.zheng {
  float: left;
  margin-top: 30px;
  margin-left: 150px;
}

.zheng-zi {
  float: left;
  margin-top: 5px;
  margin-left: 140px;
}

.fanmian {
  width: 100%;
  height: 170px;
  float: left;
  margin-top: 20px;
  background-color: white;
}

.fan {
  float: left;
  margin-top: 30px;
  margin-left: 150px;
}

.fan-zi {
  float: left;
  margin-top: 5px;
  margin-left: 140px;
}

.zheng-ti {

  .van-button {
    width: 300px;
    height: 50px;
    float: left;
    margin-top: 30px;
    margin-left: 50px;
    color: white;
    background-color: cornflowerblue;
    /*设置边框圆角 */
    border-radius: 5%;
  }
}


.camera_outer {
  position: relative;
  overflow: hidden;

  background-size: 100%;

  video,
  canvas,
  .tx_img {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
  }

  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }

  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }

  .img_bg_camera {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;

    img {
      width: 300px;
      height: 300px;
    }

    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;

      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}

</style>